package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.BoneDiagnoseAddressDao;
import cn.yunyichina.provider.bone.dao.BoneDiagnoseDao;
import cn.yunyichina.provider.bone.entity.BoneDiagnose;
import cn.yunyichina.provider.bone.entity.BoneDiagnoseAddress;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuxp on 2017/10/23.
 *
 * @param
 * @Descrition 面诊出诊安排
 */
@Service
public class DiagnoseServiceImpl {

    private static Logger logger = LoggerFactory.getLogger(DiagnoseAddressServiceImpl.class);

    private SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private BoneDiagnoseDao boneDiagnoseDao;
    @Autowired
    private BoneDiagnoseAddressDao boneDiagnoseAddressDao;

    /**
     *  yyt.bone.diagnose.list
     * @param data
     * @return
     */
    public Response listDiagnose(String data){
        Response response = new Response();
        try {
            BoneDiagnose boneDiagnose = JSONObject.parseObject(data,BoneDiagnose.class);
            boneDiagnose.setBeginConsultationTime(DateUtils.getDateTimeStr());
            List<BoneDiagnose> boneDiagnoseList = boneDiagnoseDao.select(boneDiagnose);
            //获取默认地址
            BoneDiagnoseAddress address = new BoneDiagnoseAddress();
            address.setIsDefault(1);
            address.setDoctorId(boneDiagnose.getDoctorId());
            List<BoneDiagnoseAddress> list = boneDiagnoseAddressDao.select(address);
            Map<String,Object> map = new HashMap<>();
            map.put("list",boneDiagnoseList);
            if(!list.isEmpty()) {
                map.put("address", list.get(0));
            }
            response.setResultCodeAndMessageAndResult("0","查询成功!", JsonUtils.toJsonString(map));
        }catch (Exception e){
            logger.error("获取面诊信息列表失败！",e);
            response.setResultCodeAndMessage("-1","获取面诊信息列表失败！");
        }
        return  response;
    }

    /**
     *  yyt.bone.diagnose.save
     * @param data
     * @return
     */
    public Response saveDiagnose(String data){
        Response response = new Response();
        try {
            BoneDiagnose boneDiagnose = JsonUtils.parseObject(data,BoneDiagnose.class);
            logger.info("保存号源信息，入参："+boneDiagnose.toString());
            if(boneDiagnose.getConsultationTime()!=null){
                if(compareTime(boneDiagnose.getConsultationTime())){
                    response.setResultCodeAndMessage("-3","号源时间有误！");
                    return response;
                }
            }
            //用于更新默认证金
            BoneDiagnoseAddress address = new BoneDiagnoseAddress();
            if(StringUtils.isBlank(boneDiagnose.getId())){
                //新增
                BoneDiagnose entity = new BoneDiagnose();
                entity.setDoctorId(boneDiagnose.getDoctorId());
                entity.setConsultationTime(boneDiagnose.getConsultationTime());
                entity.setDeptId(boneDiagnose.getDeptId());
                entity.setConsultationStatus(1);
                entity.setOrgId(boneDiagnose.getOrgId());
                List<BoneDiagnose> list = boneDiagnoseDao.select(entity);
                if(!list.isEmpty()){
                    response.setResultCodeAndMessage("-2","号源已存在！");
                    return response;
                }
                boneDiagnose.setId(PKGenerator.generateId());
                boneDiagnose.setUpdateTime(simpleDateFormat.format(new Date()));
                boneDiagnose.setCreatedTime(simpleDateFormat.format(new Date()));
                boneDiagnose.setConsultationStatus(1);
                boneDiagnoseDao.insert(boneDiagnose);
                response.setResultCodeAndMessage("0","新增号源成功!");
                address.setDoctorId(boneDiagnose.getDoctorId());
            }else{
                //编辑
                BoneDiagnose entity = boneDiagnoseDao.selectById(boneDiagnose.getId());
                if(entity == null){
                    response.setResultCodeAndMessage("-2","该号源不存在");
                    return response;
                }
                boneDiagnose.setUpdateTime(simpleDateFormat.format(new Date()));
                boneDiagnoseDao.update(boneDiagnose);
                address.setDoctorId(entity.getDoctorId());
            }
            //更新默认证金
            address.setIsDefault(1);
            List<BoneDiagnoseAddress> list = boneDiagnoseAddressDao.select(address);
            if(!list.isEmpty()) {
                list.get(0).setDiagnoseAmount(boneDiagnose.getConsultationFee());
                boneDiagnoseAddressDao.update(list.get(0));
            }
            response.setResultCodeAndMessage("0","修改号源成功!");
        }catch (Exception e){
            logger.error("保存号源异常！",e);
            response.setResultCodeAndMessage("-1","保存号源异常！");
        }
        return  response;
    }

    private boolean compareTime(String consultationTime) {
        logger.info("号源时间："+consultationTime);
        boolean flag = false;
        try {
            Date date = simpleDateFormat.parse(consultationTime);
            Date nowDate = new Date();
            if(nowDate.getTime()>date.getTime()){
                flag = true;
            }
        } catch (ParseException e) {
            logger.error("解析号源时间异常",e);
        }
        logger.info("号源时间对比结果："+flag);
        return  flag;
    }

    /**
     *  yyt.bone.diagnose.update
     * @param data
     * @return
     */
    public Response updateDiagnose(String data){
        Response response =new Response();
        try{
            BoneDiagnose boneDiagnose = JsonUtils.parseObject(data,BoneDiagnose.class);
            BoneDiagnose entity = boneDiagnoseDao.selectById(boneDiagnose.getId());
            if(entity == null){
                response.setResultCodeAndMessage("-2","号源不存在");
                return response;
            }
            boneDiagnose.setUpdateTime(simpleDateFormat.format(new Date()));
            boneDiagnoseDao.update(boneDiagnose);
            response.setResultCodeAndMessage("0","更新号源成功!");
        }catch (Exception e){
            logger.error("更新号源异常!",e);
        }
        return  response;
    }
}
